<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { DeleteOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndProvider } from 'vue3-dnd';

import { uploadImg } from '#/api';

import { base64ToBlob } from '../../tools';
import MoveItem from './imgMove/moveItem.vue';
// import { storeToRefs } from 'pinia';

import { addAiImageStore } from '#/store';

const addAiImage = addAiImageStore();
// const { showAddAiImageBox } = storeToRefs(addAiImage);

const formState: any = defineModel();
const mainImageThreeToFourRule = computed(
  () => formState.value.rule?.mainImageThreeToFourRule,
);

// const dspcp = ref(false);
/** 主图拖拽 */
const imageList = ref(initImage());
function initImage() {
  return (
    formState.value.mainPicList.map((item: any, index: number) => {
      return {
        url: item,
        id: index + 1,
        islodin: false,
      };
    }) || []
  );
}
const moveCard = (dragIndex: number, hoverIndex: number) => {
  const item = imageList.value[dragIndex];
  imageList.value.splice(dragIndex, 1);
  imageList.value.splice(hoverIndex, 0, item);
  // resetImageId();
};
function removeCard(index: number) {
  imageList.value.splice(index, 1);
  resetImageId();
}
function resetImageId() {
  imageList.value.forEach((item: any, index: number) => {
    item.id = index + 1;
  });
  formState.value.mainPicList = imageList.value.map((item: any) => item.url);
}
/** 主图拖拽 */

/** 主图3:4拖拽 */
const imageList34 = ref(init34image());
function init34image() {
  return (
    formState.value.mainImageThreeToFourList?.map(
      (item: any, index: number) => {
        return {
          url: item,
          id: index + 1,
          islodin: false,
        };
      },
    ) || []
  );
}
const moveCard34 = (dragIndex: number, hoverIndex: number) => {
  const item = imageList34.value[dragIndex];
  imageList34.value.splice(dragIndex, 1);
  imageList34.value.splice(hoverIndex, 0, item);
};
function removeCard34(index: number) {
  imageList34.value.splice(index, 1);
  resetImageId34();
}
function resetImageId34() {
  imageList34.value.forEach((item: any, index: number) => {
    item.id = index + 1;
  });
  formState.value.mainImageThreeToFourList = imageList34.value.map(
    (item: any) => item.url,
  );
}

const whiteBackGroundPicUrlObj = ref({
  url: formState.value.whiteBackGroundPicUrl,
  islodin: false,
});
/** 主图3:4拖拽 */

/** 1:1主图转3:4 */
function inPicTo34Image() {
  const copyimageToSet = [...formState.value.mainPicList];
  // 将copyimageToSet中的图片批量转换成3:4的图片
  // console.log('copyimageToSet', copyimageToSet);
  const get11to34imagepro = copyimageToSet.map((item: any) => {
    return new Promise((resolve) => {
      const img = new Image();
      img.src = item;
      // 设置img允许跨域
      img.crossOrigin = 'anonymous';

      img.addEventListener('load', () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
        const width = img.width;
        const height = img.height;
        const ratio = width / height;
        if (ratio < 3 / 4) {
          canvas.width = width;
          canvas.height = width * (4 / 3);
        } else {
          canvas.width = height * (3 / 4);
          canvas.height = height;
        }
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        const dataURL = canvas.toDataURL('image/png');
        resolve(dataURL);
      });
    });
  });
  Promise.all(get11to34imagepro).then((res: any) => {
    formState.value.mainImageThreeToFourList = res;
    imageList34.value = init34image();
    imageList34.value.forEach((item: any, index: number) => {
      item.islodin = true;
      const blobf: any = base64ToBlob(item.url);
      // console.log('blobf', blobf);
      const file = new File([blobf], `${`${Date.now()}${index}`}.png`, {
        type: `image/png`,
      });
      const formDatas = new FormData();
      formDatas.append('files', file);
      formDatas.append('shopId', formState.value.shopId);
      formDatas.append('offerId', formState.value.offerId);
      uploadImg(formDatas).then((res: any) => {
        item.url = res[0] || item.url;
        item.islodin = false;
        resetImageId();
      });
    });
  });
}

function upimagefunc(type: string) {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.addEventListener('change', (e: any) => {
    const file = e.target.files[0];
    // 限制最大5m
    if (file.size > 5 * 1024 * 1024) {
      return message.error('文件大小不能超过5M');
    }
    // 限制宽高比例为1:1
    const img = new Image();
    img.src = URL.createObjectURL(file);
    img.addEventListener('load', () => {
      if (
        (type === 'pic' || type === 'whiteBackGroundPicUrl') &&
        img.width !== img.height
      ) {
        return message.error('图片宽高比例必须为1:1');
      }
      // 限制图片需要为3:4
      if (type === 'threeToFour' && img.width / img.height !== 3 / 4) {
        return message.error('图片宽高比例必须为3:4');
      }

      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.addEventListener('load', (e: any) => {
        if (type === 'pic') {
          const addItem = {
            url: e.target.result,
            id: imageList.value.length + 1,
            islodin: true,
          };
          imageList.value.push(addItem);
          const formDatas = new FormData();
          formDatas.append('files', file);
          formDatas.append('shopId', formState.value.shopId);
          formDatas.append('offerId', formState.value.offerId);
          uploadImg(formDatas).then((res: any) => {
            addItem.url = res[0] || addItem.url;
            addItem.islodin = false;
            resetImageId();
          });
          // setTimeout(() => {
          //   imageList.value.find(
          //     (item: any) => item.id === addItem.id,
          //   )!.islodin = false;
          //   resetImageId();
          //   // resetImageId34();
          // }, 1000);
        }
        if (type === 'threeToFour') {
          const addItem = {
            url: e.target.result,
            id: imageList.value.length + 1,
            islodin: true,
          };
          imageList34.value.push(addItem);
          const formDatas = new FormData();
          formDatas.append('files', file);
          formDatas.append('shopId', formState.value.shopId);
          formDatas.append('offerId', formState.value.offerId);
          uploadImg(formDatas).then((res: any) => {
            addItem.url = res[0] || addItem.url;
            addItem.islodin = false;
            resetImageId34();
          });
          // setTimeout(() => {
          //   imageList34.value.find(
          //     (item: any) => item.id === addItem.id,
          //   )!.islodin = false;
          //   // resetImageId();
          //   resetImageId34();
          // }, 1000);
        }
        if (type === 'whiteBackGroundPicUrl') {
          whiteBackGroundPicUrlObj.value.islodin = true;
          whiteBackGroundPicUrlObj.value.url = e.target.result;
          const formDatas = new FormData();
          formDatas.append('files', file);
          formDatas.append('shopId', formState.value.shopId);
          formDatas.append('offerId', formState.value.offerId);
          uploadImg(formDatas).then((res: any) => {
            whiteBackGroundPicUrlObj.value.islodin = false;
            whiteBackGroundPicUrlObj.value.url =
              res[0] || whiteBackGroundPicUrlObj.value.url;
            formState.value.whiteBackGroundPicUrl = res[0] || e.target.result;
            // resetImageId34();
          });
          // setTimeout(() => {
          //   whiteBackGroundPicUrlObj.value.islodin = false;
          //   formState.value.whiteBackGroundPicUrl = e.target.result;
          // }, 1000);
        }
      });
    });
  });
  input.click();
}

function upVideoFunc() {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'video/*';
  input.addEventListener('change', (e: any) => {
    const file = e.target.files[0];
    // 限制最大5m
    if (file.size > 5 * 1024 * 1024) {
      return message.error('文件大小不能超过5M');
    }
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.addEventListener('load', (e: any) => {
      formState.value.materialvideoUrl = e.target.result;
      const formDatas = new FormData();
      formDatas.append('files', file);
      formDatas.append('shopId', formState.value.shopId);
      formDatas.append('offerId', formState.value.offerId);
      uploadImg(formDatas).then((res: any) => {
        formState.value.materialvideoUrl =
          res[0] || formState.value.materialvideoUrl;
        // formState.value.materialvideoUrl.islodin = false;
        resetImageId();
      });
    });
  });
  input.click();
}

function delVideo() {
  formState.value.materialvideoUrl = null;
}
function chenData() {
  imageList.value = initImage();
  imageList34.value = init34image();
}

watch(formState, () => {
  chenData();
});
function getAiImageCb(params: any) {
  // console.log('params', params);
  params.forEach((item: any) => {
    imageList.value[item.indexKey].url = item.newUrl;
  });
}
function openUseAiImage() {
  const getImageItem = imageList.value.map((item: any, index: number) => ({
    oldUrl: item.url,
    newUrl: item.url,
    indexKey: index,
  }));
  // console.log('getImageItem', getImageItem);
  addAiImage.openAddAiImageBox(getImageItem, getAiImageCb);
}
</script>

<template>
  <div>
    <DndProvider :backend="HTML5Backend">
      <a-form :model="formState" layout="vertical">
        <a-form-item
          :rules="[{ required: true, message: `该项为必填，请输入` }]"
          name="mainPicList"
        >
          <template #label>
            <a-space>
              <div>主图</div>
              <a-button type="primary" @click="openUseAiImage">AI作图</a-button>
            </a-space>
          </template>
          <div class="flex flex-wrap gap-2">
            <div v-for="(item, index) in imageList" :key="item.id">
              <MoveItem
                :id="item.id"
                :end="resetImageId"
                :index="index"
                :islodin="item.islodin"
                :move-card="moveCard"
                :remove-card="removeCard"
                :url="item.url"
                class-name="w-20 h-20"
              />
            </div>
            <div
              v-if="imageList.length < 5"
              class="flex h-20 w-20 cursor-pointer items-center justify-center bg-gray-300"
              @click="() => upimagefunc('pic')"
            >
              上传图片
            </div>
          </div>
        </a-form-item>
        <a-form-item
          v-if="mainImageThreeToFourRule?.isShow || true"
          :rules="[
            {
              required: !!mainImageThreeToFourRule?.mustInput,
              message: `该项为必填，请输入`,
            },
          ]"
        >
          <template #label>
            <span>主图3:4</span>
            <a-button type="link" @click="inPicTo34Image">
              从1:1主图导入
            </a-button>
          </template>
          <div class="flex flex-wrap gap-2">
            <div v-for="(item, index) in imageList34" :key="item.id">
              <MoveItem
                :id="item.id"
                :end="resetImageId34"
                :index="index"
                :islodin="item.islodin"
                :move-card="moveCard34"
                :remove-card="removeCard34"
                :url="item.url"
                class-name="w-20 h-32"
              />
            </div>
            <div
              v-if="imageList34.length < 5"
              class="flex h-32 w-20 cursor-pointer items-center justify-center bg-gray-300"
              @click="() => upimagefunc('threeToFour')"
            >
              上传3:4
            </div>
          </div>
        </a-form-item>

        <a-form-item label="主图视频">
          <!-- <template #label>
            <span>主图3:4</span>
            <a-button type="link" @click="inPicTo34Image">
              从1:1主图导入
            </a-button>
          </template> -->
          <div
            class="topmo relative flex h-32 w-20 cursor-pointer items-center justify-center overflow-hidden bg-gray-300"
          >
            <video
              v-if="formState.materialvideoUrl"
              :src="formState.materialvideoUrl"
              controls
            ></video>
            <div
              v-else
              class="flex h-full w-full items-center justify-center gap-2"
              @click="upVideoFunc"
            >
              上传视频
            </div>
            <div
              v-if="formState.materialvideoUrl"
              class="boto absolute left-0 flex h-4 w-full items-center justify-center gap-2 text-white"
            >
              <div class="flex-1 cursor-pointer text-center">
                <UploadOutlined @click="upVideoFunc" />
              </div>
              <div class="flex-1 cursor-pointer text-center" @click="delVideo">
                <DeleteOutlined />
              </div>
            </div>
          </div>
        </a-form-item>
        <a-form-item label="测评短视频">
          <a-switch v-model:checked="formState.isEvaluateOpened" />
        </a-form-item>
        <a-form-item label="白底图">
          <div class="flex flex-wrap gap-2">
            <template
              v-for="(item, index) in [whiteBackGroundPicUrlObj]"
              :key="index"
            >
              <div v-if="whiteBackGroundPicUrlObj.url">
                <MoveItem
                  :id="index"
                  :end="() => {}"
                  :index="index"
                  :islodin="item.islodin"
                  :move-card="() => {}"
                  :remove-card="
                    (_data) => {
                      whiteBackGroundPicUrlObj.url = '';
                      formState.whiteBackGroundPicUrl = '';
                    }
                  "
                  :url="item.url"
                  class-name="w-20 h-20"
                />
              </div>
            </template>
            <div
              v-if="!whiteBackGroundPicUrlObj.url"
              class="flex h-20 w-20 cursor-pointer items-center justify-center bg-gray-300"
              @click="() => upimagefunc('whiteBackGroundPicUrl')"
            >
              上传图片
            </div>
          </div>
        </a-form-item>
        <a-form-item v-if="0" label="3:4导购图">
          <div
            class="flex h-32 w-20 cursor-pointer items-center justify-center bg-gray-300"
            @click="() => upimagefunc('pic')"
          >
            上传图片
          </div>
        </a-form-item>
      </a-form>
    </DndProvider>
  </div>
</template>
<style lang="less" scoped>
.topmo {
  .boto {
    bottom: -1rem;
    background: rgb(0 0 0 / 50%);
    transition: all 0.1s;
  }

  &:hover .boto {
    bottom: 0;
  }
}
</style>
